package com.dgut.healthreportmanage.service;

import com.dgut.healthreportmanage.mapper.ReportMapper;
import com.dgut.healthreportmanage.pojo.Report;
import com.dgut.healthreportmanage.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Transactional
@Service
public class ReportServiceImpl implements ReportService{
    @Autowired
    private ReportMapper reportMapper;

    @Autowired
    private UserService userService;

    @Override
    public Report getLatestReportByUserId(int userId) {
        Report report = reportMapper.getLatestReportByUserId(userId);
        if (report == null) {
            report = new Report();
            report.setUserId(userId);
            report.setIDType("居民身份证");
            report.setState("良好");
            report.setHealthColor("绿码");
            report.setTravelColor("绿卡");
            report.setInoculated("已接种两针");
        }
        return report;
    }

    @Override
    public List<Report> getAllReports() {
        return reportMapper.getAllReports();
    }

    @Override
    public int addReport(User user, Report report) {
        int userId = userService.addUser(user);
        if (userId == 0) {
            return 0;
        }
        report.setUserId(userId);
        //防止重复提交
        Report latestReportByUserId = reportMapper.getLatestReportByUserId(userId);
        Date date = new Date();
        if (latestReportByUserId.getDate() == null ||
                !(latestReportByUserId.getDate().toString().equals(new java.sql.Date(date.getTime()).toString()))) {
            report.setDate(new java.sql.Date(date.getTime()));
            int result = reportMapper.addReport(report);
            if (result == 0) {
                return 0;
            }
        }
        else {
            return 0;
        }
        latestReportByUserId = reportMapper.getLatestReportByUserId(report.getUserId());
        if (latestReportByUserId == null) {
            return 0;
        }
        return latestReportByUserId.getReportId();
    }
}
